using UnityEngine;
using System.Collections;

public class EnemyPatrolState : State<EnemyControl>
{
    #region Singleton

    private static EnemyPatrolState instance = new EnemyPatrolState();
    public static EnemyPatrolState Instance { get { return instance; } }
    private EnemyPatrolState() { }

    #endregion

    #region Methods

    private void MoveWaypoints(EnemyControl behaviour)
    {
        Vector3 direction = behaviour.CurrentWaypoint.position - behaviour.transform.position;

        if (direction.magnitude < 1 || behaviour.IsObstacleInDetectionRange())
        {
            behaviour.NextWaypoint();
            behaviour.transform.LookAt(behaviour.CurrentWaypoint);
            behaviour.State = EnemyIdleState.Instance;
        }
        else
        {
            behaviour.moveDirection = direction.normalized * behaviour.walkSpeed;
        }
     
        behaviour.Move();
    }

    private void MoveNormal(EnemyControl behaviour)
    {
        if (behaviour.IsObstacleInDetectionRange())
            this.TurnAround(behaviour);
        else if (behaviour.IsGrounded)
            behaviour.moveDirection = behaviour.transform.forward * behaviour.walkSpeed;
        
        behaviour.Move();
    }

    private void TurnAround(EnemyControl behaviour)
    {
        behaviour.TurnAround();
        behaviour.State = EnemyIdleState.Instance;
    }

    #endregion

    #region State

    public override void OnEnterState(EnemyControl behaviour)
    {
    }

    public override void OnUpdateState(EnemyControl behaviour)
    {
        if (behaviour.IsTargetInViewRange())
            behaviour.State = EnemyAlertState.Instance;
        else if (behaviour.useWaypoints)
            this.MoveWaypoints(behaviour);
        else
            this.MoveNormal(behaviour);
    }

    public override void OnFixedUpdateState(EnemyControl behaviour)
    {
    }

    public override void OnExitState(EnemyControl behaviour)
    {
        behaviour.moveDirection = Vector3.zero;
    }

    public override void OnCollisionState(EnemyControl behaviour, Collision other)
    {
    }

    public override void OnTriggerState(EnemyControl behaviour, Collider other)
    {
        if (other.name.Contains(Constants.BORDER_NAME))
            this.TurnAround(behaviour);
    }

    #endregion
}
